package com.kefu.robot.service;

import java.util.List;
import java.util.stream.Collectors;


import cn.hutool.core.util.IdUtil;
import com.kefu.common.context.KefuContext;
import com.kefu.common.util.Assert;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Maps;
import com.kefu.basic.service.BasicShareService;
import com.kefu.chat.model.ChatUser;
import com.kefu.chat.service.ChatCacheService;
import com.kefu.chat.service.ChatFaqService;
import com.kefu.chat.vo.ChatUserParam.UserRobotAskP;
import com.kefu.common.result.Result;
import com.kefu.common.service.AbstractKefuService;
import com.kefu.robot.mapper.RobotDocNodeItemMapper;
import com.kefu.robot.mapper.RobotDocNodeItemQuestionMapper;
import com.kefu.robot.mapper.RobotDocNodeMapper;
import com.kefu.robot.model.RobotDocNode;
import com.kefu.robot.model.RobotDocNodeItem;
import com.kefu.robot.vo.RobotDocNodeItemVo;

import cn.hutool.core.util.StrUtil;

/**
 * @author CodeGenerator
 * @date 2021/10/10
 */
@Service
public class RobotDocNodeService  extends AbstractKefuService<RobotDocNode> {
    @Autowired
	RobotDocNodeMapper robotDocNodeMapper;
	@Autowired
	RobotDocNodeItemMapper robotDocNodeItemMapper;
	@Autowired
	RobotDocNodeItemQuestionMapper robotDocNodeItemQuestionMapper;
	@Autowired
	private ChatFaqService chatFaqService;
	@Autowired
	private BasicShareService basicShareService;
    @Autowired
    private ChatCacheService chatCacheService;
	
	public void deleteNode(String nodeId) {
		robotDocNodeMapper.deleteByPrimaryKey(nodeId);
		RobotDocNodeItem model = new RobotDocNodeItem();
		model.setNodeId(nodeId);
		robotDocNodeItemMapper.delete(model);
	}
	public List<RobotDocNodeItem> getItemList(String nodeId) {
		return robotDocNodeItemMapper.selectList(Wrappers.lambdaQuery(RobotDocNodeItem.class).eq(RobotDocNodeItem::getNodeId,nodeId).orderByAsc(RobotDocNodeItem::getCreateTime));
	}
	
	/**
	 * 获取第一个节点信息
	 * @param docId
	 * @return
	 */
	public RobotDocNode getFirstNode(UserRobotAskP param,ChatUser user) {
		RobotDocNode model = new RobotDocNode();
		model.setDocId(param.getDocId());
		model.setIsFirst(1);
		RobotDocNode node= findByModel(model)
								.stream()
								.findFirst()
								.orElse(null);
		if(node==null) {
			return null;
		}
		if(node.getNodeType()==5) {//接口调用
			user.setNodeParamCache(Maps.newHashMap());
			String interfaceId=node.getNodeContent();
			String businessId=node.getNodeId();
			user.getNodeParamCache().put("nodeId", node.getNodeId());
			user.getNodeParamCache().put("pid", user.getPid());
			user.getNodeParamCache().put("userId", user.getUserId());
			user.getNodeParamCache().put("params", user.getParams());
			chatCacheService.setUser(user);
			Result<RobotDocNode> result=basicShareService.doRemote(interfaceId, businessId, user.getNodeParamCache(), new TypeReference<Result<RobotDocNode>>() {});
			if(result.getData()!=null) {
				node=result.getData();
				node.setIsFirst(1);
				node.setDocId(param.getDocId());
			}
			
		}else {
			node.setItemList(getItemList(node.getNodeId()));
		}
		if (StrUtil.isNotBlank(node.getFaqId())) {
			node.setChatFaq(chatFaqService.getById(node.getFaqId()));
        }
		return node;
	}
	
	/**
	 * 获取下一个节点得配置
	 */
	public RobotDocNode getNextNode(UserRobotAskP param,ChatUser user) {
		RobotDocNode node = null;
		if(StrUtil.isNotBlank(param.getNodeId())){
			node = findById(param.getNodeId());
		}
		RobotDocNodeItem item = robotDocNodeItemMapper.selectByPrimaryKey(param.getItemId());
		if(item != null && StrUtil.isNotBlank(item.getNextNodeId())){
			node= findById(item.getNextNodeId());
		}
		if(node!=null) {
			if(node.getNodeType()==5) {
				user.setNodeParamCache(user.getNodeParamCache()==null?Maps.newHashMap():user.getNodeParamCache());
				if(!user.getNodeParamCache().containsKey("nodeId")) {
					user.getNodeParamCache().put("nodeId",param.getNodeId());
				}
				String key=param.getItemBindCode();
				String value=param.getItemBindValue();
				if(StringUtils.isNoneBlank(key)) {
					user.getNodeParamCache().put(key,StringUtils.isBlank(value)?param.getQuestion():value);
				}
				chatCacheService.setUser(user);
				String interfaceId=node.getNodeContent();
				String businessId=node.getNodeId();
				//要求返回的内容中  nodeId任然是传递的NodeId,
				Result<RobotDocNode> result=basicShareService.doRemote(interfaceId, businessId, user.getNodeParamCache(), new TypeReference<Result<RobotDocNode>>() {});
				if(result.getData()!=null) {
					node=result.getData();
					node.setDocId(param.getDocId());
				}
				
			}else {
				node.setItemList(getItemList(node.getNodeId()));
			}
		}
		return node;
	}
	public void addItem(RobotDocNodeItem info) {
		robotDocNodeItemMapper.insertSelective(info);
	}
	public void deleteItem(String id) {
		robotDocNodeItemMapper.deleteByPrimaryKey(id);
	}
	public void updateItem(RobotDocNodeItem info) {
		robotDocNodeItemMapper.updateByPrimaryKeySelective(info);
	}
	
	public List<RobotDocNodeItemVo> selectListVoByNodeId(String nodeId){
		return robotDocNodeItemMapper.selectListByNodeId(nodeId).stream().map(item->{
			return RobotDocNodeItemVo.builder()
					.nodeItem(item)
					.synonyms(robotDocNodeItemQuestionMapper.selectListByItemId(item.getItemId()))
					.build();
		}).collect(Collectors.toList());
	}

	public RobotDocNode copy(String nodeId){
		KefuContext context = KefuContext.getKefuContext();

		RobotDocNode node=robotDocNodeMapper.selectById(nodeId);
		Assert.isNull(node,"节点不存在");
		Assert.isTrue(node.getIsFirst()==1,"开始节点不可以复制");

		node.setNodeId(IdUtil.simpleUUID());
		node.setCreateTime(context.getNow());
		node.setBindName(null);
		robotDocNodeMapper.insert(node);

		List<RobotDocNodeItem> items=robotDocNodeItemMapper.selectListByNodeId(nodeId);
		node.setItemList(items);
		items.stream().forEach(item->{
			item.setNodeId(node.getNodeId());
			item.setCreateTime(context.getNow());
			item.setItemId(IdUtil.simpleUUID());
			item.setNextNodeId(null);
			item.setBindValue(null);
			robotDocNodeItemMapper.insert(item);
		});

		return node;
	}
}
